package demo.gateway.metric;

import org.reactivestreams.Publisher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import reactor.core.publisher.Mono;

/**
 * ServerHttpResponseDecorator是Spring WebFlux中的一个响应装饰器类，用于包装和扩展ServerHttpResponse的功能。
 * 它遵循装饰器模式，允许我们在不修改原始响应对象的情况下添加新的行为。
 */
public class SSEResponseDecorator extends ServerHttpResponseDecorator {

    static Logger logger = LoggerFactory.getLogger(SSEResponseDecorator.class);

    private boolean firstResponseRecorded = false;
    long firstResponseTime = 0 ;
    long lastResponseTime = 0;

    public SSEResponseDecorator(ServerHttpResponse delegate) {
        super(delegate);
    }

    /**
     * 使用给定的Publisher将消息体写入底层HTTP层。
     * @param bodyPublisher the body content publisher
     * @return
     */
    @Override
    public Mono<Void> writeWith(Publisher<? extends DataBuffer> bodyPublisher) {
        return Mono.from(bodyPublisher).flatMap(buffer -> {
            if (!firstResponseRecorded) {
                firstResponseRecorded = true;
                firstResponseTime = System.currentTimeMillis();
                logger.info("SSE(server send event) 首次响应时间: " + firstResponseTime);
            }
            return getDelegate().writeWith(Mono.just(buffer));
        });
    }

    @Override
    public Mono<Void> setComplete() {
        lastResponseTime = System.currentTimeMillis();
        logger.info("SSE(server send event) 最后一次响应时间: " + lastResponseTime);
        return super.setComplete();
    }
}
